package messenger;

import javax.swing.JFrame;

import java.awt.Desktop;
import java.awt.EventQueue;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenu;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.border.EtchedBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class gui {

	JFrame frmMessenger; 
	DefaultListModel<String> ulist = new DefaultListModel<String>();
	DefaultListModel<String> mlist = new DefaultListModel<String>();
	DefaultListModel<String> alist = new DefaultListModel<String>();
	UserAccount user = new UserAccount();
	JTextArea list_1;
	CommChannel client;
	Timer timer;
	JEditorPane editorPane;
	String serverIP = "127.0.0.1";
	static Desktop desktop;
	private final JPanel contentPanel = new JPanel();
	
	/**
	 * @return array of strings these are the usernames in the contact list
	 */
	public void listNames() {
		if(user.isLoggedIn()){
			if(ulist.getSize()!=user.getContacts().size()){
				ulist.clear();
				Object[] temps = user.getContacts().toArray();
				for (int i = 0; i < user.getContacts().size(); ++i) {
					ulist.addElement(((Contact) temps[i]).getUserName());
				}
			}
		}
	}
	/**
	 * @return array of strings these are the usernames in the temp contact list
	 */
	public void listContacts() {
		if(user.isLoggedIn()){
			if(alist.getSize()!=client.getTmpContacts().size()){
				alist.clear();
				Object[] temps = client.getTmpContacts().toArray();
				for (int i = 0; i < client.getTmpContacts().size(); ++i) {
					alist.addElement(((Contact) temps[i]).getUserName());
				}
			}
		}
	}
	
	/**
	 * @return array of strings these are the messages displayed
	 */
	public void listMessages() {
		if(user.isLoggedIn()){
			if(!user.getTmpMessages().isEmpty())
				for(Message m : user.getTmpMessages())
					list_1.append(m.getFrom()+": "+m.getBody()+"\n\n");
			user.getTmpMessages().clear();
		}
	}
	
	/**
	 * @wbp.parser.entryPoint
	 */
	public static void guiMain() {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					gui window = new gui();
					window.frmMessenger.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	
	
	/**
	 * Create the application.
	 * 
	 * @param user
	 */
	public gui() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 * 
	 * @param user
	 */
	private void initialize() {
		serverIP=ChatManager.serverIP;
		frmMessenger = new JFrame();
		frmMessenger.setTitle("Messenger");
		frmMessenger.setBounds(100, 100, 800, 600);
		frmMessenger.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JMenuBar menuBar = new JMenuBar();
		frmMessenger.setJMenuBar(menuBar);

		JMenu mnMenu = new JMenu("Menu");
		menuBar.add(mnMenu);

		int delay = 1000; //milliseconds
		  ActionListener taskPerformer = new ActionListener() {
		      public void actionPerformed(ActionEvent evt) {
		          //...Perform a task...
		    	  listNames();
		    	  listMessages();
		    	  listContacts();
		    	  if(client==null || !client.isAlive())frmMessenger.setTitle("Messenger - Disconnected!");
		    	  else
		    		  frmMessenger.setTitle("Messenger - Connected");
		      }
		  };
		  timer = new Timer(delay, taskPerformer);
	      timer.setInitialDelay(delay);
	      timer.start(); 
		  
		
		JMenuItem mntmLogin = new JMenuItem("Login");
		mntmLogin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				JTextField userName = new JTextField();
				JPasswordField password = new JPasswordField();
				final JComponent[] inputs = new JComponent[] {
				                new JLabel("Username"),
				                userName,
				                new JLabel("Password"),
				                password
				};
				JOptionPane.showMessageDialog(null, inputs, "Login", JOptionPane.PLAIN_MESSAGE);
				char[] p = password.getPassword();
				StringBuilder st = new StringBuilder();
				for(char t : p)
					st.append(t);
				user=new UserAccount(userName.getText(), st.toString());
				
				if(user==null || !user.isLoggedIn()){
					JOptionPane.showMessageDialog(null,
						    "Bad Password!");
				}else{
					listNames();
					client = new CommChannel(serverIP, 4444, user);
					client.start();
					client.setCommand(CommCommand.LOGIN);
					if(client!=null)
						frmMessenger.setTitle("Messenger - Connected");
				}
			}
		});
		mntmLogin.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
			}
		});
		mnMenu.add(mntmLogin);

		JMenuItem mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				user.saveState();
				System.exit(0);
			}
		});
		mntmExit.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {

			}
		});
		
		JMenuItem mntmFindContact = new JMenuItem("Find Contact");
		mntmFindContact.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JTextField userName = new JTextField();
				final JComponent[] inputs = new JComponent[] {
				                new JLabel("Username to find?"),
				                userName
				};
				JOptionPane.showMessageDialog(null, inputs, "Find Contact", JOptionPane.PLAIN_MESSAGE);
				if(user.findContact(userName.getText())==null){
					client.setFindUser(userName.getText());
					client.setCommand(CommCommand.GETCONTACT);
				}
			}
		});
		
		JMenuItem mntmBrowseContacts = new JMenuItem("Browse Contacts");
		mntmBrowseContacts.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				client.setCommand(CommCommand.GETALL);
				JList<String> clist = new JList<String>(alist);
				JScrollPane scrollPane3 = new JScrollPane(clist);
				scrollPane3.setBounds(200, 24, 574, 401);
				
				final JComponent[] inputs = new JComponent[] {
				                new JLabel("UsersList"),
				                scrollPane3
				};
				//UserFavorites dialog = new UserFavorites(ulist);
				//dialog.setVisible(true);
				JOptionPane.showMessageDialog(null, inputs, "Browse Contacts", JOptionPane.PLAIN_MESSAGE);
				if(user.findContact(clist.getSelectedValue())==null){
					client.setFindUser(clist.getSelectedValue());
					client.setCommand(CommCommand.GETCONTACT);
				}
			}
		});
		mnMenu.add(mntmBrowseContacts);
		mnMenu.add(mntmFindContact);
		
		JMenuItem mntmSetup = new JMenuItem("Setup");
		mntmSetup.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JTextField userName = new JTextField();
				JPasswordField password = new JPasswordField();
				JTextField pid = new JTextField();
				JTextField firstName = new JTextField();
				JTextField lastName = new JTextField();
				JTextField email = new JTextField();
				JTextField phone = new JTextField();
				JTextField gyear = new JTextField();
				final JComponent[] inputs = new JComponent[] {
				                new JLabel("Username"),
				                userName,
				                new JLabel("Password"),
				                password,
				                new JLabel("pid"),
				                pid,
				                new JLabel("Firstname"),
				                firstName,
				                new JLabel("Lastname"),
				                lastName,
				                new JLabel("Phone"),
				                phone,
				                new JLabel("Email"),
				                email,
				                new JLabel("Graduation Year"),
				                gyear
				};
				JOptionPane.showMessageDialog(null, inputs, "Setup", JOptionPane.PLAIN_MESSAGE);
				char[] p = password.getPassword();
				StringBuilder st = new StringBuilder();
				for(char t : p)
					st.append(t);
				if(userName.getText().isEmpty()|st.toString().isEmpty()){
					JOptionPane.showMessageDialog(null, "Must have username and password", "Setup", JOptionPane.INFORMATION_MESSAGE);
				}else{
					user = new UserAccount(userName.getText(), st.toString());
					user.setpId(pid.getText());
					user.setFirstName(firstName.getText());
					user.setLastName(lastName.getText());
					user.setPhone(phone.getText());	
					user.seteMail(email.getText());
					if(!gyear.getText().isEmpty())
						user.setYear(Integer.parseInt(gyear.getText()));
					client = new CommChannel(serverIP, 4444, user);
					client.start();
					client.setCommand(CommCommand.ADDCCONTACT);
				}
			}
		});
		mnMenu.add(mntmSetup);
		mnMenu.add(mntmExit);

		JMenu mnTools = new JMenu("Help");
		menuBar.add(mnTools);
		
		JMenuItem mntmAbout = new JMenuItem("About");
		mntmAbout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final ImageIcon icon1 = new ImageIcon("220px-Honey_badger.jpg");
				final JComponent[] inputs = new JComponent[] {
		                new JLabel("Messenger program by:\nGroup 42")
					};
		JOptionPane.showMessageDialog(null, inputs, "Setup", JOptionPane.INFORMATION_MESSAGE,icon1);
			}
		});
		
		JMenuItem mntmNewMenuItem = new JMenuItem("User Guide");
		mntmNewMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try{ 
		            String url = "http://code.google.com/p/cop3330-final/wiki/ChatManager"; 
		            java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); 
		          } 
		          catch (java.io.IOException e1) { 
		              System.out.println(e1.getMessage()); 
		          } 
			}
		});
		mnTools.add(mntmNewMenuItem);
		mnTools.add(mntmAbout);
		frmMessenger.getContentPane().setLayout(null);
		final JList<String> list = new JList<String>(ulist);
		list.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				@SuppressWarnings("unchecked")
				JList<String> list = (JList<String>)arg0.getSource();
		        if (arg0.getClickCount() == 2) {
		        	String[] u = list.getSelectedValue().toString().split(" ");
		        	Contact tuser = user.findContact(u[0]);		        	
		            final JComponent[] inputs = new JComponent[] {	
			                new JLabel("Userinfo for:  "+tuser.userName),
			                new JLabel("Name: "+tuser.firstName+" "+tuser.lastName),
			                new JLabel("Email: "+tuser.eMail),
			                new JLabel("Phone: "+tuser.phone),
			                new JLabel("Pid: "+tuser.pId)
			};
			JOptionPane.showMessageDialog(null, inputs, "User Details", JOptionPane.PLAIN_MESSAGE);
		        } 
			}
		});
		list.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		list.setBounds(10, 24, 180, 473);
		JScrollPane scrollPane = new JScrollPane(list);
		scrollPane.setBounds(10, 24, 180, 473);
		frmMessenger.getContentPane().add(scrollPane);

		list_1 = new JTextArea();
		list_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		list_1.setBounds(200, 24, 574, 401);
		JScrollPane scrollPane2 = new JScrollPane(list_1);
		scrollPane2.setBounds(200, 24, 574, 401);
		frmMessenger.getContentPane().add(scrollPane2);

		editorPane = new JEditorPane();
		editorPane.setBounds(200, 436, 518, 94);
		editorPane
				.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		frmMessenger.getContentPane().add(editorPane);

		JLabel lblContacts = new JLabel("Contacts");
		lblContacts.setBounds(10, 11, 104, 14);
		frmMessenger.getContentPane().add(lblContacts);

		JLabel lblMessages = new JLabel("Messages");
		lblMessages.setBounds(200, 11, 297, 14);
		frmMessenger.getContentPane().add(lblMessages);

		JButton btnNewButton = new JButton("Send");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String username;
				if(((username = (String) list.getSelectedValue())!=null) && (editorPane.getText()!=null)){
					Message tmp = new Message(username, user.userName, "", editorPane.getText());
					client.setOutMessage(tmp);
					client.setCommand(CommCommand.SEND);
					editorPane.setText(null);
					user.getTmpMessages().add(tmp);
				}
			}
		});
		btnNewButton.setBounds(717, 507, 67, 23);
		frmMessenger.getContentPane().add(btnNewButton);
		
		JButton btnDeleteContact = new JButton("Delete Contact");
		btnDeleteContact.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(list.getSelectedValue()!=null){
					int n = JOptionPane.showConfirmDialog(
						    null,
						    "Deleting Contact "+list.getSelectedValue()+". Are you sure?",
						    "Delete Contact",
						    JOptionPane.YES_NO_OPTION);
					if(n == JOptionPane.OK_OPTION){
						user.deleteContact(list.getSelectedValue());
						user.saveState();
					}
				}
			}
		});
		btnDeleteContact.setBounds(10, 508, 180, 23);
		frmMessenger.getContentPane().add(btnDeleteContact);
	}
}
